// pages/authorizedLogin/authorizedLogin.js
var a = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    sessionKey: '',
    code: '',
    appid: '',
    showModal: true,
  },

  getUser: function (e) {
    // console.log('e',e.detail);
    var _this = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          wx.showLoading({
            title: '正在授权...',
          })
          wx.login({
            success: function (data) {
              wx.request({
                url: a.apiUrl("user/login"),
                method: "POST",
                data: {
                  userinfo: e.detail,
                  code: data.code,
                  ru_id: a.globalData.ru_id,
                },
                success: function (res) {
                  // console.log('res', res.data)
                  wx.hideLoading()
                  // wx.switchTab({
                  //   url: '../index/index',
                  //  })
                  wx.setStorageSync("_user", res.data.userinfo)
                  if (res.data.token == 0) {
                    _this.setData({
                      showModal: false
                    })
                  } else {
                    _this.setData({
                      userInfo: e.detail.userInfo,
                      sessionKey: res.data.session_key,
                      appid: res.data.appid,
                    })

                    try {
                      wx.setStorage({
                          key: "token",
                          data: res.data.token
                        }),
                        wx.setStorage({
                          key: "openid",
                          data: res.data.openid
                        });
                    } catch (err) {
                      console.log('捕获到错误，重新加载')
                      e.data = 0;
                      wx.setStorage({
                        key: "token",
                        data: res.data.split.token
                      }), wx.setStorage({
                        key: "openid",
                        data: res.data.openid
                      });
                      console.log('重新加载成功')
                    }

                    wx.switchTab({
                      url: '../index/index',
                    })
                  }
                }
              })
            }
          })
        }else{
          wx.showToast({
            title: '授权失败！',
            icon: 'none',
            duration: 1500
          })
        }
      }
    })
  },

  getPhoneNumber: function (e) {
    let _this = this;
    let userInfor = wx.getStorageSync("_user");
    wx.checkSession({
      success: (res) => {
        wx.request({
          url: a.apiUrl('user/phoneNumber'),
          data: {
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            ru_id: a.globalData.ru_id,
            code: _this.data.code,
            userinfo: userInfor
          },
          method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            // console.log('getPhoneNumber', res.data)
				console.log(res)
            if (res.data.status == true) {
              wx.showToast({
                title: '手机号绑定成功！',
                icon: 'none',
                duration: 1500
              })
              wx.setStorage({
                key: "token",
                data: res.data.token
              });
              wx.setStorage({
                key: "openid",
                data: res.data.openid
              });
              wx.switchTab({
                url: '../index/index',
              })
            } else if (res.data.status == false) {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 1500
              })
              return;
            }
          },
          fail: function (err) {
            console.log(err);
          }
        })
      },
      fail: (error) => {
        wx.login({})
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.login({
      success: function (data) {
        that.setData({
          code: data.code,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})